package ld.dao.impl;

import ld.dao.UserDao;
import ld.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author: Liudao
 * @Date: 2022-08-09-15:14
 * @Description:
 */
@Repository
public class UserDaoImpl implements UserDao, RowMapper<User> {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Override
    public List<User> findAll() {
        return jdbcTemplate.query("select * from user",this);
    }

    @Override
    public User findById(int id) {
        return jdbcTemplate.queryForObject("select * from user where uid = ?",this,id);
    }

    @Override
    public void add(User user) {
        jdbcTemplate.update("insert into user values (null,?,?)",user.getUsername(),user.getBalance());
    }

    @Override
    public void update(User user) {
        jdbcTemplate.update("update user set username = ?,balance = ? where uid = ?",user.getUsername(),user.getBalance(),user.getUid());
    }

    @Override
    public void delete(int id) {
        jdbcTemplate.update("delete from user where uid = ?",id);
    }


    @Override
    public User mapRow(ResultSet resultSet, int i) throws SQLException {
        return new User(resultSet.getInt("uid"),
                resultSet.getString("username"),
                resultSet.getInt("balance"));
    }
}
